package com.nyt.org.common.utils;


import com.alibaba.fastjson.JSON;
import com.nyt.org.modules.api.constant.Status;
import com.nyt.org.modules.api.model.BaseResponse;
import com.nyt.org.modules.api.model.PublicRequest;
import com.nyt.org.modules.api.model.PublicResponse;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

public class HttpUtil {

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || ip.indexOf(":") > -1) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = null;
            }
        }
        return ip;
    }


    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {
            int readlen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        String body = new String(buffer, charEncoding);
        return body;
    }

    public  static void sucessResponse(ServletResponse response, PublicRequest publicReq, Object body) {
        Writer writer = null;
        try {
            // 准备返回信息
            BaseResponse respData = new BaseResponse(
                    new PublicResponse(publicReq.getMethod(), publicReq.getAccesskey(), publicReq.getRequestid(),
                            DateUtil.nowFormat("yyyyMMddHHmmss"), "00000", "成功", ""),
                    null);
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("publicresponse", respData);
            hashMap.put("body", body);
            writer.write(JSON.toJSONString(hashMap));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public  static void loseResponse(ServletResponse response, PublicRequest publicReq, /*Object body,*/String wrongMsg) {
        Writer writer = null;
        try {
            // 准备返回信息
            BaseResponse respData = new BaseResponse(
                    new PublicResponse(publicReq.getMethod(), publicReq.getAccesskey(), publicReq.getRequestid(),
                            DateUtil.nowFormat("yyyyMMddHHmmss"), "11111", wrongMsg, ""),
                    null);
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("publicresponse", respData);
            hashMap.put("body", /*body*/"");
            writer.write(JSON.toJSONString(hashMap));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
